﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Configuration;
using System.Collections;
using System.Text;
using System.Data.SqlClient;

namespace Cache
{
    public class HttpCache : ICache
    {
        public object Cache
        {
            get
            {
                if (HttpContext.Current != null)
                {
                    return HttpContext.Current.Cache;
                }
                else
                {
                    return null;
                }
            }
        }

        public bool Enabled
        {
            get
            {
                return Boolean.Parse(ConfigurationManager.AppSettings.Get("IsCacheEnabled"));
            }
        }
        
        public void Insert(string key, object value)
        {
            var cache = (System.Web.Caching.Cache)Cache;
            cache.Add(key, value, null, DateTime.MaxValue, new TimeSpan(), System.Web.Caching.CacheItemPriority.Normal, null);
        }

        public void Delete(string key)
        {
            var cache = (System.Web.Caching.Cache)Cache;
            cache.Remove(key);
        }

        public object Fetch(string key)
        {
            object result = null;

            var cache = (System.Web.Caching.Cache)Cache;
            result = cache.Get(key);

            return result;
        }

        public List<string> GetAllKeys()
        {
            List<string> keys = new List<string>();
            var cache = (System.Web.Caching.Cache)Cache;
            IDictionaryEnumerator enumerator = cache.GetEnumerator();

            while (enumerator.MoveNext())
            {
                keys.Add(enumerator.Key.ToString());
            }

            return keys;
        }

        public void Reset()
        {
            if (Enabled && Cache != null)
            {
                var cache = (System.Web.Caching.Cache)Cache;
                var keys = GetAllKeys();

                for (int i = 0; i < keys.Count; i++)
                {
                    cache.Remove(keys[i]);
                }
            }            
        }

        public string GenCacheKey(string command, List<SqlParameter> parameters)
        {
            StringBuilder result = new StringBuilder(command);

            if (parameters != null)
            {
                foreach (var parameter in parameters)
                {
                    result.AppendFormat("|{0}={1}", parameter.ParameterName, parameter.Value);
                }
            }

            return result.ToString();
        }
    }
}
